//package com.sky.controller;
//
//import com.sky.dto.SysLoginByPhoneDTO;
//import com.sky.dto.SysLoginDTO;
//import com.sky.entity.SysUser;
//import com.sky.result.Result;
//import com.sky.service.SysUserService;
//import com.sky.utils.JwtTokenUtils;
//import com.sky.utils.RandomCodeUtil;
//import com.sky.vo.CodeVO;
//import com.sky.vo.SysUserLoginVO;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.core.context.SecurityContextHolder;
//
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//
//
//@RestController
//@RequestMapping("/sys")
//@Slf4j
//@Api(tags ="sys登录")
//public class SysUserLoginController {
//    @Autowired
//    private SysUserService sysUserService;
//    @Autowired
//    private RedisTemplate redisTemplate;
//    @Autowired
//    private AuthenticationManager authenticationManager;
////    @Autowired
////    @Qualifier("sysUserServiceImpl")
////    private UserDetailsService userDetailsService;
////    @Autowired
////    private PasswordEncoder passwordEncoder;
//
//    @GetMapping("/getVerifyCode")
//    @ApiOperation(notes = "获取验证码", value = "获取验证码")
//    public Result<CodeVO> getVerifyCode() {
//        String code = RandomCodeUtil.getCode(6);
//        log.info("验证码：{}", code);
//        String key = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(key,code,30,TimeUnit.MINUTES);
////        BufferedImage image = defaultKaptcha.createImage(code);
////        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
////            ImageIO.write(image, "JPEG", out);
////            byte[] imageBytes = out.toByteArray();
////            Base64.Encoder encoder = Base64.getEncoder();
////            String imageString = new String(encoder.encode(imageBytes), StandardCharsets.UTF_8);
////            return Objects.requireNonNull(R.success().put("data", imageString)).put("key", key);
////        } catch (IOException e) {
////            throw new RuntimeException("验证码获取失败");
////        }
//        return Result.success(new CodeVO(code,key));
//    }
//
//    @PostMapping("/login")
//    @ApiOperation("登录")
//    public Result<SysUserLoginVO> login(@RequestBody SysLoginDTO sysLoginDTO) {
//        log.info("用户登录：{}", sysLoginDTO);
//        if(sysLoginDTO.getUsername()==null){
//            return Result.error("用户名不能为空");
//        }
//        if(sysLoginDTO.getPassword()==null){
//            return Result.error("密码不能为空");
//        }
//        Object code = redisTemplate.opsForValue().get(sysLoginDTO.getKey());
//        if(code==null){
//            return Result.error("验证码已失效");
//        }
//        if(!code.toString().equals(sysLoginDTO.getVerifyCode())){
//            return Result.error("验证码错误");
//        }
//        Authentication authentication = null;
//
////        UsernamePasswordAuthenticationToken authenticationToken =
////                new UsernamePasswordAuthenticationToken(sysLoginDTO.getUsername(), sysLoginDTO.getPassword());
////        authentication = authenticationManager.authenticate(authenticationToken);
//        //ThreadLocal 存Security 上下文
////        UserDetails userDetails = userDetailsService.loadUserByUsername(sysLoginDTO.getUsername());
////        if(!passwordEncoder.matches(sysLoginDTO.getPassword(), userDetails.getPassword())) {
////            throw new BadCredentialsException("密码错误");
////        }
//        try {
//             authentication = authenticationManager.authenticate(
//                    new UsernamePasswordAuthenticationToken(
//                            sysLoginDTO.getUsername(),
//                            sysLoginDTO.getPassword()
//                    )
//            );
//        } catch (AuthenticationException e) {
//            return Result.error(e.getMessage()); // 统一认证失败消息
//        }
////        Authentication authentication = new UsernamePasswordAuthenticationToken(
////                userDetails,
////                null,
////                userDetails.getAuthorities()
////        );
//        SecurityContextHolder.getContext().setAuthentication(authentication);
//        Object principal = authentication.getPrincipal();
//        SysUser user = new SysUser();
//        BeanUtils.copyProperties(principal, user);
//        String token = JwtTokenUtils.createToken(user.getUsername());
//        SysUserLoginVO sysUserLoginVO = new SysUserLoginVO();
//        BeanUtils.copyProperties(user,sysUserLoginVO);
//        sysUserLoginVO.setToken(token);
//        log.info("登录成功:{}",sysUserLoginVO);
//        return Result.success(sysUserLoginVO);
//    }
//
//    @PostMapping("/register")
//    @ApiOperation("注册")
//    public Result register(@RequestBody @Validated SysUser sysUser){
//        log.info("注册用户：{}",sysUser);
//        return sysUserService.register(sysUser);
//    }
//
//    @PostMapping("/loginByPhone")
//    @ApiOperation("通过手机验证码登录")
//    public Result<SysUserLoginVO> loginByPhone(@RequestBody SysLoginByPhoneDTO sysLoginByPhoneDTO){
//        log.info("手机验证码登录，{}",sysLoginByPhoneDTO);
//        if(sysLoginByPhoneDTO.getPhone()==null){
//            return Result.error("手机号不能为空");
//        }
//        Object code = redisTemplate.opsForValue().get(sysLoginByPhoneDTO.getPhone());
//        if(code==null){
//            return Result.error("验证码已失效");
//        }
//        if(!code.toString().equals(sysLoginByPhoneDTO.getVerifyCode())){
//            return Result.error("验证码错误");
//        }
//        log.info("发送的验证：{}",code);
//        SysUser sysUser = sysUserService.loginByPhone(sysLoginByPhoneDTO.getPhone());
//        String token = JwtTokenUtils.createToken(sysUser.getUsername());
//        SysUserLoginVO sysUserLoginVO = new SysUserLoginVO();
//        BeanUtils.copyProperties(sysUser,sysUserLoginVO);
//        sysUserLoginVO.setToken(token);
//        return Result.success(sysUserLoginVO);
//    }
//    @GetMapping("/user/{id}")
//    @ApiOperation("查询用户")
//    public Result<SysUser> getUser(@PathVariable Integer id){
//        SysUser user= sysUserService.getById(id);
//        return Result.success(user);
//    }
// }
